//
//  UUModuleController.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 22/01/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUModuleController.h"
#import "AppDelegate.h"

// 不需要和当前用户同步的 Manager
#import "UULoginManager.h"
#import <UUFoundation/UUHybridManager.h>
#import <UUFoundation/UUPersistenceManager.h>

// 需要和当前用户同步的 Manager
#import <UUFoundation/DKDataManager.h>
#import "UUSupplierManager.h"
#import "UUUserManager.h"
#import "UUFleetManager.h"
#import "UUCarManager.h"
#import "UUDriverManager.h"
#import "UUKeeperManager.h"
#import "UUOrderManager.h"
#import "UUWalletManager.h"
#import "UUProductManager.h"
#import "UUIntentOrderManager.h"
#import "UUNotificationManager.h"
#import "UUBadgeManager.h"

typedef enum : NSUInteger {
    UUMessageTypeSupplierReview     = 1, // 供应商审核状态发生变化
    UUMessageTypeCar                = 4, // 车辆状态变化
    UUMessageTypeFleet,                  // 车队状态变化
    UUMessageTypeDriver,                 // 司机状态变化
    UUMessageTypeKeeper,                 // 管理员状态变化
    UUMessageTypeForceLogout,            // 强制将用户踢下线
    UUMessageTypeUser,                   // 用户信息变化
    UUMessageTypeProduct            = 13,// 产品信息变化
    
} UUMessageType;

@interface UUModuleController ()

@property (nonatomic, assign) BOOL isLogged;

@end

@implementation UUModuleController

- (void)setupWithLaunchOptions:(NSDictionary *)launchOptions {
    [GetHybridManager() syncHybridResource];
    [self incrementForCommon];
}

- (void)userDidLogin {
    [self clearAllModules];
    
    self.isLogged = YES;
    
    [self incrementForPrivate];
    
    [UUBadgeManager sharedInstance];
}

- (void)userDidLogout {
    [GetLoginManager() logout];
    
    self.isLogged = NO;
    
    [self clearAllModules];
}

- (void)awakeFromBackground {
    [self incrementForCommon];
    
    if (self.isLogged) {
        NSTimeInterval timeInterval = [[GetPersistenceManager().userPrivateDefaults objectForKey:@"_ModuleController_AllIncrementLatestTime"] doubleValue];
        NSDate *latestDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
        if ([latestDate dateInWeek:0 month:0 hour:0 minute:3] == NO) {
            [self incrementForPrivate];
            [GetPersistenceManager().userPrivateDefaults setObject:@([[NSDate date] timeIntervalSince1970]) forKey:@"_ModuleController_AllIncrementLatestTime"];
        }
    }
}

- (void)clearAllModules {
    [DKDataManager cancelAllRequests]; // 取消所有的网络请求
    [GetPersistenceManager() clear]; // 清理持久化配置缓存
    
    [UUBaseModel clearHelper];
    
    [UUSupplierManager removeInstance];
    [UUUserManager removeInstance];
    [UUCarManager removeInstance];
    [UUFleetManager removeInstance];
    [UUDriverManager removeInstance];
    [UUKeeperManager removeInstance];
    [UUOrderManager removeInstance];
    [UUWalletManager removeInstance];
    [UUProductManager removeInstance];
    [UUIntentOrderManager removeInstance];
    [UUNotificationManager removeInstance];
    [UUBadgeManager removeInstance];
}

- (void)reachabilityNetworkStatusChanged:(BOOL)isReachable isSlowlyNetworking:(BOOL)isSlowlyNetworking {
    if (isReachable) {
        [self incrementForCommon];
        
        if (self.isLogged) {
            [self incrementForPrivate];
        }
    }
}

- (void)receiveMessage:(NSDictionary *)message {
    DKLog(@"Received 消息：%@", message);
    
    UUMessageType messageType = [[message valueForKey:@"message_type"] integerValue];
    switch (messageType) {
        case UUMessageTypeSupplierReview:
            [GetUserManager() setNeedsUpdateUserInfo];
            [GetUserManager() asyncFetchUserInfoWithCompleteBlock:nil];
            break;
        case UUMessageTypeCar:
            [GetCarManager() asyncUpdateCars];
            break;
        case UUMessageTypeFleet:
            [GetFleetManager() asyncUpdateFleets];
            break;
        case UUMessageTypeDriver:
            [GetDriverManager() asyncUpdateDrivers];
            break;
        case UUMessageTypeKeeper:
            [GetKeeperManager() asyncUpdateKeepers];
            break;
        case UUMessageTypeUser:
            [GetUserManager() setNeedsUpdateUserInfo];
            [GetUserManager() asyncFetchUserInfoWithCompleteBlock:nil];
            break;
        case UUMessageTypeForceLogout:
            POST_MSG_WITH_OBJ_DICT(NOTIFICATION_USER_NEED_LOGOUT, message[@"desc"], @{LOGOUT_REASON_KEY:@(UULogoutReasonTypeForceLogout)});
            break;
        case UUMessageTypeProduct:
            [GetProductManager() asyncUpdateProducts];
            break;
        default:
            DKLog(@"收到了暂时不支持的内推消息 %ld", messageType);
    }
    
    [GetNotificationManager() asyncUpdateUnreadCount];
}

#pragma mark - Private methods

- (void)incrementForPrivate {
    [GetUserManager() setNeedsUpdateUserInfo];
    [GetUserManager() asyncFetchUserInfoWithCompleteBlock:nil];
    [GetFleetManager() asyncUpdateFleets];
    [GetCarManager() asyncUpdateCars];
    [GetDriverManager() asyncUpdateDrivers];
    [GetKeeperManager() asyncUpdateKeepers];
    [GetOrderManager() asyncUpdateOrders];
    [GetSupplierManager() asyncUpdatePeakSeasons];
    [GetProductManager() asyncUpdateProducts];
    [GetProductManager() asyncUpdateProductPackages];
    [GetNotificationManager() asyncUpdateUnreadCount];
}

- (void)incrementForCommon {
    [GetCarCategoryManager() asyncUpdateCarCategory];
}

@end
